﻿#ifndef IPCCOM_H
#define IPCCOM_H

#include <QObject>
#include <QLocalSocket>
#include <QLocalServer>
#include <QByteArray>

/*
示例：
// Qt 服务端
IPCCom server("MyLocalSocket", true);
connect(&server, &IPCCom::messageReceived, [](const QByteArray &msg){ qDebug() << "Server recv:" << msg; });
server.start();

// Qt 客户端
IPCCom client("MyLocalSocket", false);
connect(&client, &IPCCom::connected, [](){ qDebug() << "connected!"; });
client.start();
client.send("hello from client");
*/


/**
 * @brief The IPCCom class
 * 一个基于 QLocalSocket/QLocalServer 的进程间通信类
 * 支持服务端和客户端两种模式，跨进程通信更简单
 */
class IPCCom : public QObject
{
    Q_OBJECT
public:
    // 如果 isServer=true，则创建本地服务端；否则创建客户端连接
    explicit IPCCom(const QString &serverName, QObject *parent = nullptr);
    ~IPCCom();


    bool open(); // 启动服务端或连接客户端
    void close(); // 停止服务端或客户端

    bool isOpen() const;
    QString serverName() const;


    bool send(const QByteArray &data); // 发送数据


signals:
    void errorOccurred(const QString &err);
    void connected();
    void disconnected();


private slots:
    void onNewConnection();
    void onReadyRead();
    void onDisconnected();
    void onError(QLocalSocket::LocalSocketError err);

    virtual void onDataReceived(const QByteArray &data) = 0;


private:
    QString m_serverName;
    QLocalServer *m_server = nullptr;
    QLocalSocket *m_socket = nullptr;
};

#endif // IPCCOM_H
